import {
  ipcMain,
  dialog,
  BrowserWindow,
  app,
  ipcRenderer,
  net,
} from "electron";
import { getPreloadFile, winURL } from "../config/static-path";
import { updater } from "./hot-updater";
import DownloadFile from "./download-file";
import Update from "./check-update";
import config from "@config/index";
import Store from "electron-store";
const { clipboard, shell } = require("electron");
const store = new Store();
const path = require("path");

import {
  readFile,
  writeFile,
  openDialog,
  reNameFile,
  openSaveDialog,
  openFileChooseDialog,
  makeDir,
} from "./fs";
export const useMainDefaultIpc = () => {
  const defaultIpc = () => {
    const allUpdater = new Update();

    ipcMain.on("change-window-size", (event, args) => {
      const win = BrowserWindow.fromWebContents(event.sender);

      switch (args) {
        case "minimizeWin":
          win.minimize();
          break;
        case "maximize":
          win.isMaximized() ? win.unmaximize() : win.maximize();
          break;
        case "closeWin":
          win.close();
        default:
          break;
      }
    });
    ipcMain.on("quitAll", (event, args) => {
      app.quit();
    });

    ipcMain.on("close-other", (event, args) => {
      const win = BrowserWindow.fromWebContents(event.sender);
      console.log("win", win.id, event.sender.id);
      let all = BrowserWindow.getAllWindows();
      all.forEach((window) => {
        console.log("a", window, window.id);
        if (window.id != win.id) {
          window.close();
        }
      });
    });
    ipcMain.on("copyData", (event, data) => {
      clipboard.writeText(data);
      // hello i am a bit of text!'
    });
    ipcMain.on("set-ignore-mouse-events", (event, { ignore, options }) => {
      const win = BrowserWindow.fromWebContents(event.sender);
      win.setIgnoreMouseEvents(ignore, options);
    });
    ipcMain.on("setStore", (_, { key, value }) => {
      // console.log("app.getPath('userData')", app.getPath("userData"));

      try {
        store.set(key, value);
        _.returnValue = true;
      } catch (error) {
        _.returnValue = false;
      }
    });
    ipcMain.on("getTemplatePath", (_: any, key) => {
      // BrowserWindow.fromWebContents(event.sender)
      _.returnValue = path.join(process.cwd(), `/lib/${key}`);
    });
    ipcMain.on("getStore", (_: any, key) => {
      let value = store.get(key);
      _.returnValue = value;
    });
    ipcMain.on("deleteStore", (_: any, key) => {
      let value = store.delete(key);
      _.returnValue = value;
    });
    ipcMain.handle("openDialog", async (event) => {
      let res: any = await openDialog(
        BrowserWindow.fromWebContents(event.sender)
      );
      if (res.canceled) return false;
      return {
        path: res.filePaths[0],
        // name: path.basename(res.filePaths[0], ".md"),
        name: path.basename(res.filePaths[0]),
      };
    });
    ipcMain.handle("openSaveDialog", async (event, arg) => {
      let res: any = await openSaveDialog(
        BrowserWindow.fromWebContents(event.sender),
        arg
      );
      if (res.canceled) return false;

      return res.filePath;
    });
    ipcMain.handle("openFileChooseDialog", async (event, arg) => {
      let res: any = await openFileChooseDialog(
        BrowserWindow.fromWebContents(event.sender),
        arg
      );
      return res;
    });
    ipcMain.handle("readFile", async (event, args) => {
      return await readFile(args);
    });
    ipcMain.handle("writeFile", async (event, args) => {
      return await writeFile(args.path, args.data);
    });
    ipcMain.handle("reNameFile", async (event, args) => {
      return await reNameFile(args.oldPath, args.newPath);
    });
    ipcMain.handle("makeDir", async (event, args) => {
      return await makeDir(args.path);
    });

    ipcMain.handle("IsUseSysTitle", async () => {
      return config.IsUseSysTitle;
    });
    ipcMain.handle("app-close", (event, args) => {
      app.quit();
    });
    ipcMain.handle("check-update", (event) => {
      allUpdater.checkUpdate(BrowserWindow.fromWebContents(event.sender));
    });
    ipcMain.handle("confirm-update", () => {
      allUpdater.quitAndInstall();
    });
    ipcMain.handle("open-messagebox", async (event, arg) => {
      const res = await dialog.showMessageBox(
        BrowserWindow.fromWebContents(event.sender),
        {
          type: arg.type || "info",
          title: arg.title || "",
          buttons: arg.buttons || [],
          message: arg.message || "",
          noLink: arg.noLink || true,
        }
      );
      return res;
    });
    ipcMain.handle("open-errorbox", (event, arg) => {
      dialog.showErrorBox(arg.title, arg.message);
    });
    ipcMain.handle("start-server", async () => {
      dialog.showErrorBox("error", "API is obsolete");
    });
    ipcMain.handle("stop-server", async (event, arg) => {
      dialog.showErrorBox("error", "API is obsolete");
    });
    ipcMain.handle("hot-update", (event, arg) => {
      updater(BrowserWindow.fromWebContents(event.sender));
    });
    ipcMain.handle("start-download", (event, msg) => {
      new DownloadFile(
        BrowserWindow.fromWebContents(event.sender),
        msg?.downloadUrl || ""
      ).start();
    });
    let MainWindow = null;
    let ChildWin = null;
    ipcMain.handle("open-win", (event, arg) => {
      if (ChildWin) {
        ChildWin.close();
        ChildWin = null;
      }
      ChildWin = new BrowserWindow({
        titleBarStyle: config.IsUseSysTitle ? "default" : "hidden",
        height: 595,
        useContentSize: true,
        width: 1140,
        autoHideMenuBar: true,
        minWidth: 842,
        frame: config.IsUseSysTitle,
        show: false,
        webPreferences: {
          sandbox: false,
          webSecurity: false,
          // 如果是开发模式可以使用devTools
          devTools: process.env.NODE_ENV === "development",
          // 在macos中启用橡皮动画
          scrollBounce: process.platform === "darwin",
          preload: getPreloadFile("preload"),
        },
      });
      // 开发模式下自动开启devtools
      if (process.env.NODE_ENV === "development") {
        ChildWin.webContents.openDevTools({ mode: "right", activate: true });
      }
      ChildWin.loadURL(winURL + `#${arg.url}`);
      ChildWin.once("ready-to-show", () => {
        ChildWin.show();
        ChildWin.maximize();

        ChildWin.on("close", () => {
          ipcMain.removeListener("infoFromMain", () => {
            console.log("removeinfoFromMain");
          });
          ipcMain.removeAllListeners("infoFromMain");
          ChildWin.webContents.removeListener("infoFromMain", () => {
            console.log("removeinfoFromMain");
          });
          ipcMain.removeAllListeners("infoToMain");
          console.log("close!");
          ChildWin = null;
          if (MainWindow && MainWindow.webContents) {
            // ipcMain.removeAllListeners("infoToMain");
            MainWindow.webContents.send("ChildWinClose", true);
          }
        });
      });
      // 渲染进程显示时触发
      ChildWin.once("show", () => {
        ChildWin.webContents.send("send-data", arg.sendData);
        // ChildWin.webContents.send("infoFromMain", "");
        if (MainWindow && MainWindow.webContents) {
          console.log("openChildWined");

          MainWindow.webContents.send("openChildWined", true);
          ipcMain.on("infoToMain", (event, msg) => {
            console.log("infoToMain了");
            MainWindow = BrowserWindow.fromWebContents(event.sender);

            if (ChildWin) {
              ChildWin.webContents.send("infoFromMain", msg);
            }
          });
        }
      });
    });

    ipcMain.on("infoToMain", (event, msg) => {
      console.log("infoToMain了");
      MainWindow = BrowserWindow.fromWebContents(event.sender);

      if (ChildWin) {
        ChildWin.webContents.send("infoFromMain", msg);
      }
    });
    ipcMain.on("setFullScreen", (event, msg) => {
      if (ChildWin) {
        ChildWin.setFullScreen(msg);
      }
    });

    ipcMain.on("setMainWindow", (event, arg) => {
      MainWindow = BrowserWindow.fromWebContents(event.sender);
    });

    ipcMain.on("previewPageInit", (event, arg) => {
      if (MainWindow && MainWindow.webContents) {
        console.log("previewPageInit");
        MainWindow.webContents.send("previewPageInitEdit", true);
      }
    });

    ipcMain.on("openBrowserUrl", (event, arg) => {
      shell.openExternal(arg);
    });
  };
  return {
    defaultIpc,
  };
};
